package MyArithmetic;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

class Solution1 {
    public List<List<Integer>> fourSum(int[] nums, int target) {
        List<List<Integer>> listAll = new ArrayList<>();
        Arrays.sort(nums);
        for (int i = 0; i < nums.length; i++) {
            if (i > 0 && nums[i - 1] == nums[i]) {
                continue;
            }
            for (int j = i + 1; i < nums.length; j++) {
                if (j > 0 && nums[j - 1] == nums[j]) {
                    continue;
                }
                int left = j + 1;
                int right = nums.length - 1;

                while (left < right && left < nums.length && right > j) {
                    int sum = nums[left] + nums[right] + nums[j] + nums[i];
                    if (sum > target) {
                        right--;
                    } else if (sum < target) {
                        left++;
                    } else {
                        List<Integer> list1 = new ArrayList<>();
                        list1.add(nums[left]);
                        list1.add(nums[right]);
                        list1.add(nums[i]);
                        list1.add(nums[j]);
                        listAll.add(list1);

                        while ((left < right && nums[right] == nums[right - 1])) {
                            right--;
                        }
                        while ((left < right && nums[left] == nums[left + 1])) {
                            left++;

                        }
                        right--;
                        left++;
                    }
                }
            }
        }
        return listAll;
    }
}
